#define SAFEVOLTAGE 10

#include <io.h>
#include <msp430x16x.h>
#include <signal.h>

#include "pay.h"

#include "../main.h"
#include "../log/log.h"
#include "../adc/adc.h"
#include "../timing/timing.h"

interrupt(PORT1_VECTOR) payload_event() {
  unsigned short paydata;

  P2OUT|=0x01;

  statusVar[SV_PAYX_PENDING]=0xFF;

  //adcEnable(1);
  paydata=adcSample(0x03, 4); //get sample from P6.4
  //adcDisable();

  statusVar[SV_PAYX_DATA1]=(int)((paydata & 0xFF00)>>8);
  statusVar[SV_PAYX_DATA2]=(int)(paydata & 0x00FF);

  chooseLog();

  //Re-enable interrupt
  P1IFG=0;
  P1IE=0xFF;

  P2OUT&=0xFE;
}

/*
NOTE: The reference voltage used for sampling (avcc 0-5v) may vary, should be checked.
*/

int payload_init(int voltage, char channel) {
  int i;
  float startRatio, ratio, deviance;

//Clear Support and HV on
  P1DIR=255;
  P1OUT=0;

//Let HV set equal 111
  P2DIR=255;
  P2OUT=7;

//Step 1 - Set Reset to high and wait a short time
  P1OUT=P1OUT | 0x80;
  for (i=0;i<1000;i++) {
    nop();
  }
  P1OUT=P1OUT & 0x7F;

//Step 2 - Set Support to high and wait
  P1OUT=P1OUT | 0x20;
  for (i=0;i<1000;i++) {
    nop();
  }
  P1OUT=P1OUT & 0xDF;

//Step 3 - Check that Input and Output voltages are near zero and signal event is cleared
  adcEnable(0);

  if (adcSample(1,0)>SAFEVOLTAGE) return 1;
  if (adcSample(3,0)>SAFEVOLTAGE) return 2;
  if (P1OUT & 0x2) return 3;

//Step 4 - Set High Voltage pin to ON
  P1OUT=P1OUT | 0x08;

//Step 5 - Check ratio of input to output voltage stays constant
  startRatio=((float)adcSample(1,0))/((float)adcSample(3,0));
  for (i=0;i<6000;i++) {
    waitms(100);
    ratio=((float)adcSample(1,0))/((float)adcSample(3,0));
    deviance=(ratio-startRatio)/startRatio;
    if (deviance<0) deviance=-deviance;
    if (deviance>0.01) return 4;
  }

  adcDisable();

//Step 6 - Set voltage of high voltage components
  P2OUT=voltage;
}

#ifdef STANDALONE
int main () {
  payload_init('x');

  P1DIR=0;
  P1SEL=0;
  P1IE=255;
  P6DIR=255;

  while(1) {
    P6OUT=255-P6OUT;
  }
}
#endif
